package com.example.rbq.service

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.example.rbq.R
import kotlinx.android.synthetic.main.activity_b.*


class BActivity : AppCompatActivity() {

    private var service: MyService? = null
    private var isBind = false

    private var conn = object : ServiceConnection {
        override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) {
            isBind = true
            val myBinder = p1 as MyService.MyBinder
            service = myBinder.service
            Log.i("xiao", "ActivityB - onServiceConnected")
            val num = service!!.getRandomNumber()
            Log.i("xiao", "ActivityB - getRandomNumber = $num");
        }

        override fun onServiceDisconnected(p0: ComponentName?) {
            isBind = false
            Log.i("xiao", "ActivityB - onServiceDisconnected")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_b)

        btn_bind_service_b.setOnClickListener {
            val intent = Intent(this, MyService::class.java)
            intent.putExtra("from","ActivityB")
            Log.i("xiao", "----------------------------------------------------------------------")
            Log.i("xiao", "ActivityB 执行 bindService");
            bindService(intent, conn, Context.BIND_AUTO_CREATE)
        }
        btn_unbind_service_b.setOnClickListener {
            if(isBind){
                Log.i("xiao", "----------------------------------------------------------------------")
                Log.i("xiao", "ActivityB 执行 unbindService");
                unbindService(conn)
            }
        }
        btn_finish_b.setOnClickListener {
            Log.i("xiao", "----------------------------------------------------------------------")
            Log.i("xiao", "ActivityB 执行 finish");
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i("xiao", "ActivityB - onDestroy")
    }
}